package com.zlt.appparking.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class MapUtil {
    @Autowired
    private RestTemplate restTemplate;
    /**
     * 发送请求
     *
     * @param serverUrl 请求地址
     */
    private static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    //将地址转换成经纬度
    public static Map getLonAndLat(String address, String key) throws UnsupportedEncodingException {
        String address1 = URLEncoder.encode(address, "utf-8");
        // 返回输入地址address的经纬度信息, 格式是 经度,纬度
        String queryUrl = "http://restapi.amap.com/v3/geocode/geo?key=" + key + "&address=" + address1;
        // 高德接口返回的是JSON格式的字符串
        String queryResult = getResponse(queryUrl);
        Map<String, BigDecimal> map = new HashMap<String, BigDecimal>();
        JSONObject obj = JSONObject.parseObject(queryResult);
        if (obj.get("status").toString().equals("1")) {
            JSONObject jobJSON = JSONObject.parseObject(obj.get("geocodes").toString().substring(1, obj.get("geocodes").toString().length() - 1));
            String location = jobJSON.get("location").toString();
            String[] lonAndLat = location.split(",");
            if (lonAndLat != null && lonAndLat.length == 2) {
                map.put("lng", new BigDecimal(lonAndLat[0]));
                map.put("lat", new BigDecimal(lonAndLat[1]));
            }
            return map;
        } else {
            throw new RuntimeException("地址转换经纬度失败，错误码：" + obj.get("infocode"));
        }
    }

    /**
     * 获取省市
     * @param longitude
     * @param latitude
     * @return
     */
    public static String getProvinceAndCity(BigDecimal longitude, BigDecimal latitude,String key) {
        String url = null;
        try {
            url = "http://restapi.amap.com/v3/geocode/regeo?output=JSON&characterEncoding=utf-8&location=" + longitude + "," + latitude
                    + "&key=" + key + "&radius=0&extensions=base";
            String response = getResponse(url);
            JSONObject jsonObject = JSONObject.parseObject(response);
            if(jsonObject!=null){
                Object regeocode = jsonObject.get("regeocode");
                 if(regeocode!=null){
                      JSONObject jsonObject1 = JSONObject.parseObject(regeocode.toString());
                        if(jsonObject1!=null){
                          Object addressComponent = jsonObject1.get("addressComponent");
                         JSONObject jsonObject2 = JSONObject.parseObject(addressComponent.toString());
                         if(jsonObject2!=null){
                        StringBuilder address=new StringBuilder();
                        address.append(jsonObject2.get("province")) ;
                        address.append(jsonObject2.get("city"));
                        return address.toString();
               }} }}
        else throw new RuntimeException("未找到相匹配的地址！");
        }catch (Exception e) {
            e.printStackTrace();
        }

        return "-1";
    }

    //将经纬度转换成地址
    /**
     * 将经纬度getLng， getLat 通过getAMapByLngAndLat方法转换地址
     *
     * @param getLng 经度
     * @param getLat 纬度
     * @param key    高德地图应用key
     * @return 地址名称
     * @throws Exception
     */
    public static String getAMapByLngAndLat(BigDecimal getLng, BigDecimal getLat, String key) throws Exception {
        String url;
        try {
            url = "http://restapi.amap.com/v3/geocode/regeo?output=JSON&location=" + getLng + ","
                    + getLat + "&key=" + key + "&radius=0&extensions=base";
            String queryResult = getResponse(url); // 高德接品返回的是JSON格式的字符串
            // 将获取结果转为json数据
            JSONObject obj = JSONObject.parseObject(queryResult);
//            System.out.println("obj为：" + obj);
            if (obj.get("status").toString().equals("1")) {
                // 如果没有返回-1
                JSONObject regeocode = obj.getJSONObject("regeocode");
                if (regeocode.size() > 0) {
                    // 在regeocode中拿到 formatted_address 具体位置
                    return regeocode.get("formatted_address").toString();
                } else {
                    throw new RuntimeException("未找到相匹配的地址！");
                }
            } else {
                throw new RuntimeException("请求错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "-1";
    }

        //根据经纬度算出两个点之间的距离

    /**
     * 根据两个定位点的经纬度算出两点间的距离
     *
     * @param startLonLat 起始经纬度
     * @param endLonLat   结束经纬度（目标经纬度）
     * @param key         高德地图应用key
     * @return 两个定位点之间的距离
     */
    public static Long getDistance(String startLonLat, String endLonLat, String key) {
        // 返回起始地startAddr与目的地endAddr之间的距离，单位：米
        Long result = new Long(0);
        String queryUrl = "http://restapi.amap.com/v3/distance?key=" + key + "&origins=" + startLonLat + "&destination=" + endLonLat;
        String queryResult = getResponse(queryUrl);
        JSONObject obj = JSONObject.parseObject(queryResult);
        JSONArray ja = obj.getJSONArray("results");
        JSONObject jobO = JSONObject.parseObject(ja.getString(0));
        result = Long.parseLong(jobO.get("distance").toString());
        return result;
    }

}
